`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date: 2025/04/10 22:24:28
// Design Name: 
// Module Name: fifo_2_mem
// Project Name: 
// Target Devices: 
// Tool Versions: 
// Description: 
// 
// Dependencies: 
// 
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
// 
//////////////////////////////////////////////////////////////////////////////////


module fifo_2_mem(
    input wire clk, //系统时钟
    input wire rst_n, //全局复位
    input wire[15:0]fifo_dout,
    input wire [9:0] fifo_rd_data_count,
    output reg fifo_read_en,
    output reg [7:0] mem_addr, //地址线
    output reg [15:0] mem_data, //数据线
    output reg mem_we //写使能信号
    );
    // State machine states
    localparam IDLE = 3'b000, READ_FIFO = 3'b001, WRITE_MEM = 3'b010, ADD_addr = 3'b011, INIT = 3'b100,READ_FIFO_2 = 3'b101;

    reg [2:0] state;

    // Combined sequential and combinational logic
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            state <= INIT;
            mem_we <= 1'b0;
            mem_data <= 16'b0;
            fifo_read_en <= 1'b0;
            mem_addr <= 8'b0;
        end else begin
            case (state)
                INIT: begin
                    mem_addr <= 8'b0;
                    if (fifo_rd_data_count > 0)
                        state <= READ_FIFO;
                    else
                        state <= IDLE;
                end
                IDLE: begin
                    mem_we <= 1'b0;
                    mem_data <= 16'b0;
                    fifo_read_en <= 1'b0;
                    if (fifo_rd_data_count > 0)
                        state <= READ_FIFO;
                end
                READ_FIFO: begin
                    fifo_read_en <= 1'b1;
                    state <= READ_FIFO_2;
                end
                READ_FIFO_2: begin
                    fifo_read_en <= 1'b0;
                    state <= WRITE_MEM;
                end

                WRITE_MEM: begin
                    mem_we <= 1'b1;
                    mem_data <= fifo_dout;
                    state <= ADD_addr;
                end
                ADD_addr: begin
                    mem_we <= 1'b0;
                    mem_addr <= mem_addr + 1'b1;
                    if (fifo_rd_data_count == 0)
                        state <= IDLE;
                    else
                        state <= READ_FIFO;
                end
                default: begin
                    state <= IDLE;
                end
            endcase
        end
    end
endmodule

